﻿using vJoyInterfaceWrap;

namespace QAQ
{
    class JoyControl
    {
        // Declaring one joystick (Device id 1) and a position structure. 
        public vJoy joystick;
        private vJoy.JoystickState iReport;
        public uint id = 1;
        public string sta;
        public const uint KeyZ = 0x1;
        public const uint Key_Down = 0x1 << 1;
        
        
            
        //initializer
        public JoyControl()
        {
            joystick = new vJoy();         
           
            iReport = new vJoy.JoystickState();
            if (!joystick.vJoyEnabled())
            {
                sta="vJoy driver not enabled: Failed Getting vJoy attributes.";
                return;
            }
            else
                sta= "Vendor: " + joystick.GetvJoyManufacturerString() + "\nProduct :" + joystick.GetvJoyProductString() + "\nVersion Number:" + joystick.GetvJoySerialNumberString();
            
            iReport.AxisXRot = 16500;
            iReport.AxisYRot = 16500;
            iReport.AxisZRot = 16500;
            iReport.AxisX = 16500;
            iReport.AxisY = 16500;
            iReport.AxisZ = 16500;
            if (!joystick.UpdateVJD(id, ref iReport))
            {
                joystick.AcquireVJD(id);
            }

        }

        


        public void Key(uint k)
        {
            KeyDown(k);
            System.Threading.Thread.Sleep(24);
            KeyUp(k);
        }

        public void KeyUp(uint k)
        {
            iReport.bDevice = (byte)id;
            iReport.Buttons &= ~((k) & (~Key_Down));
            //if KEY_DONW is turned on
            if (Key_Down == (k & Key_Down))
            {
                iReport.AxisY = 16500;
            }

            /// Feed the driver with the position packet - is fails then wait for input then try to re-acquire device
            if (!joystick.UpdateVJD(id, ref iReport))
            {
                joystick.AcquireVJD(id);
            }
        }

        public void KeyDown(uint k)
        {
            iReport.bDevice = (byte)id;
            iReport.Buttons |= ((k) & (~Key_Down));
            //if KEY_DONW is turned on
            if (Key_Down == (k & Key_Down) )
            {
                iReport.AxisY = 33000;
            }

            /// Feed the driver with the position packet - is fails then wait for input then try to re-acquire device
            if (!joystick.UpdateVJD(id, ref iReport))
            {
                joystick.AcquireVJD(id);
            }
        }

    }
}
